import { url } from '@/common/js/url'

export function request(path, query, method, contentType = null) {
	return new Promise((resolve, reject) => {
		let types = '';
		if (method == 'POST' && !contentType) {
			types = 'application/x-www-form-urlencoded'
		} else if (method == 'POST' && contentType) {
			types = contentType
		} else {
			types = 'application/json';
		}
		// #ifdef MP-WEIXIN
		const accountInfo = uni.getAccountInfoSync();
		// #endif
		const token = uni.getStorageSync('token')
		var header
		if (token !== null && token !== '' && token !== undefined) {
			header = {
				'X-Requested-With': 'XMLHttpRequest', // 触发ajax请求
				'Content-Type': types,
				'Accept': 'application/json',
				'Authorization': 'bearer' + token,
				// #ifdef MP-WEIXIN
				'appid': accountInfo.miniProgram.appId
				// #endif
			}
		} else {
			header = {
				'X-Requested-With': 'XMLHttpRequest', // 触发ajax请求
				'Content-Type': types,
				'Accept': 'application/json',
				// #ifdef MP-WEIXIN
				'appid': accountInfo.miniProgram.appId
				// #endif
			}
		}
		uni.request({
			url: url(path), //仅为示例，并非真实接口地址。
			data: query,
			method: method,
			header: header,
			success: (res) => {
				if (res.statusCode === 200) {
					resolve(res.data)
				} else {
					if (res.statusCode === 401) {
						uni.removeStorageSync('token')
						uni.showModal({
							content: '尚未登入！',
							confirmText: '立即登入',
							success: res => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/ucenter/pages/person/index'
									})
								}
							}
						})
					}
					reject(res)
				}
			},
			fail: (err) => {
				reject(err)
			}
		});
	})
}